import citycode from '@/assets/citycode.json';

interface NestedItem {
  code: string;
  name: string;
  children: NestedItem[];
}

export const kvCityCode = citycode;

export const plainCityCode = (function plainJson(kv) {
  return Object.keys(kv).map(k => ({ code: k, name: kvCityCode[k] }));
})(kvCityCode);

export const nestedCityCode: NestedItem[] = (function nestedJson(
  plain: { code: string; name: string }[],
) {
  const json: NestedItem[] = [];

  plain.forEach(val => val.code.endsWith('0000') && json.push({ ...val, children: [] }));

  // 遍历所有的省 并从数组中取出对应的市
  json.forEach(province => {
    const provinceCode = province.code.slice(0, 2);
    plain.forEach(val => {
      if (
        !val.code.endsWith('0000') &&
        val.code.endsWith('00') &&
        val.code.startsWith(provinceCode)
      ) {
        province.children.push({ ...val, children: [] });
      }
    });
  });

  // 遍历所有的市 并从数组中取出对应的区
  json.forEach(province => {
    if (province.children.length === 0) {
      const cityCode = province.code.slice(0, 2);
      plain.forEach(val => {
        if (
          !val.code.endsWith('0000') &&
          !val.code.endsWith('00') &&
          val.code.startsWith(cityCode)
        ) {
          province.children.push({ ...val, children: [] });
        }
      });
    }

    province.children.forEach(city => {
      const cityCode = city.code.slice(0, 4);
      plain.forEach(val => {
        if (
          !val.code.endsWith('0000') &&
          !val.code.endsWith('00') &&
          val.code.startsWith(cityCode)
        ) {
          city.children.push({ ...val, children: [] });
        }
      });
    });
  });
  return json;
})(plainCityCode);

export const citycode2plainJson = (code: string) =>
  [ `${ code.slice(0, 2) }0000`, `${ code.slice(0, 4) }00`, `${ code }` ]
    .map(cc => ({ code: cc, name: kvCityCode[cc] }))
    .filter(item => item.name);
